package com.yuan.java.reg;

import org.junit.Test;

public class IpTest {

    @Test
    public void testip() {
        System.out.println(isInRange("192.168.1.127", "192.168.1.64/26"));
        System.out.println(isInRange("192.168.1.2", "192.168.0.0/23"));
        System.out.println(isInRange("192.168.0.1", "192.168.0.0/24"));
        System.out.println(isInRange("172.26.0.2", "172.0/222"));
    }

    public static boolean isInRange(String ip, String ipReg) {
        String[] ips = ip.split("\\.");
        String[] ipRegs = ipReg.split("\\.");
        boolean flag = false;
        for (int i = 0; i < ipRegs.length; ++i) {
            String ipor = ips[i];
            String ipreg = ipRegs[i];
            if (!ipreg.contains("/")) {
                flag = ipor.equals(ipreg);
            } else {
                String[] iprange = ipreg.split("/");
                int ipint = Integer.valueOf(ipor);
                int ip1 = Integer.valueOf(iprange[0]);
                int ip2 = Integer.valueOf(iprange[1]);
                flag = ipint >= ip1 && ipint <= ip2;
            }
            if (!flag) {
                break;
            }
        }
        return flag;
    }
}